const router = require("koa-router")({
  prefix: "/api"
});
const orderModel = require("../../db/models")["order"];
const addressModel = require("../../db/models")["address"];
const userModel = require("../../db/models")["user"];
router.post("/auth", ctx => {
  ctx.body = {
    code: 200,
    data: ctx.$$user.username || "kyaru"
  };
});

router.post("/user", async ctx => {
  const id = ctx.$$user.id;
  const password = ctx.request.body.password;
  const user = await userModel.update({ password }, { where: { id } });
  ctx.body = {
    code: 200,
    data: user
  };
});
router.get("/user", async ctx => {
  const page = ctx.query.page || 1;
  const u = await userModel.findAndCountAll();
  const user = await userModel.findAll({
    limit: 10,
    offset: 10 * (page - 1)
  });
  ctx.body = {
    code: 200,
    data: {
      list: user,
      total: u.count
    }
  };
});
router.get("/auth", async ctx => {
  let id = ctx.$$user.id;
  const order = await orderModel.findAll({ where: { userId: id }, include: "goods" });
  const address = await addressModel.findAll({ where: { userId: id } });
  const userInfo = await userModel.findOne({ where: { id } });
  ctx.body = {
    code: 200,
    data: {
      userInfo,
      address,
      order
    }
  };
});

module.exports = router;
